package net.zjitc.bookshop15.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.zjitc.bookshop15.pojo.book;
import net.zjitc.bookshop15.service.bookService;
import net.zjitc.bookshop15.util.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author 董熠涛
 * @date 2025/4/28 13:21
 */
@RestController
public class BookController {

    @Autowired
    private bookService bookservice;

    ApiResponse apiResponse = new ApiResponse();

    @Autowired
    private StringRedisTemplate  redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    ObjectMapper objectMapper = new ObjectMapper();

    /*
        * 查询所有书籍
      */
    @RequestMapping("/book")
    @PreAuthorize("hasAnyAuthority('sys:book:selectall')")
    public ApiResponse selectAllBooks(){
        List<book> books = bookservice.selectAllBooks();
        apiResponse.oK("Success",books);
        return apiResponse;
    }

    /*
     * 根据id查询书籍
     */
    @GetMapping("/book/{id}")
    @PreAuthorize("hasAnyAuthority('sys:book:select')")
    public ApiResponse selectBookOne(@PathVariable Integer id) throws JsonProcessingException {
        System.out.println("id:"+id);

        /*
         * 实现Redis二级缓存
         */
        String bookFromRedis = stringRedisTemplate.opsForValue().get("book_" + id);

        if (bookFromRedis != null) {
            System.out.println("从Redis中获取了数据");
            book b = objectMapper.readValue(bookFromRedis, book.class);
            apiResponse.oK("Success",b);
            return apiResponse;
        }

        book bookBySelect = bookservice.selectBookOne(id);
        String s = objectMapper.writeValueAsString(bookBySelect);
        stringRedisTemplate.opsForValue().set("book_" + id,s);

        apiResponse.oK("Success",bookBySelect);
        return apiResponse;
    }
}
